import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/even/check_refresh_even.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/bean/check_in_record_brower_for_type_response_bean.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/unmarked/check_in_record_brower_for_unmarked_view_model.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/widgets/check_in_record_brower_grid_widget.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/widgets/check_in_record_brower_list_widget.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/widgets/check_in_record_brower_top_mode_tabs_widget.dart';
import 'package:e_reception_flutter/ui/mark/make_mark/make_mark_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import '../../check_in_record_brower_page.dart';

/// 打卡记录浏览-未标记
///
/// @author: zengxiangxi
/// @createTime: 1/12/21 4:29 PM
/// @specialDemand:
class CheckInRecordBrowerForUnmarkedPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CheckInRecordBrowerForUnmarkedPage";

  @override
  _CheckInRecordBrowerForUnmarkedPageState createState() =>
      _CheckInRecordBrowerForUnmarkedPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      CheckInRecordBrowerForUnmarkedPage(),
      routeName: CheckInRecordBrowerForUnmarkedPage.ROUTER,
    );
  }
}

class _CheckInRecordBrowerForUnmarkedPageState
    extends BasePagerState<CheckInRecordBrowerForTypeListItemBean,CheckInRecordBrowerForUnmarkedPage>
    with AutomaticKeepAliveClientMixin,VgPlaceHolderStatusMixin {

  CheckInRecordBrowerForUnmarkedViewModel _viewModel;

  PageController _pageController;

  TopModeTabsType _mode = TopModeTabsType.grid;


  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    _viewModel = CheckInRecordBrowerForUnmarkedViewModel(this);
    _pageController =
        PageController(initialPage: _mode == TopModeTabsType.grid ? 0 : 1);
    _viewModel.refresh();
    _streamSubscription = CheckInRecordBrowerPageState.of(context).multiRefreshStreamController?.stream?.listen((event) {
      _viewModel?.refreshMultiPage();
    });
  }

  @override
  void dispose() {
    _pageController?.dispose();
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        CheckInRecordBrowerTopModeTabsWidget(
          isShowIgnore: true,
          mode: _mode,
          onGridTap: (mode) {
            _animateToPage(0);
          },
          onListTap: (mode) {
            _animateToPage(1);
          },
          onIgnore: (){
            _viewModel?.ignoreFaceHttp(context);
          },
        ),
        Expanded(
          child: _toPageViewWidget(),
        )
      ],
    );
  }

  void _animateToPage(int page) {
    _pageController?.animateToPage(page,
        duration: Duration(milliseconds: 200), curve: Curves.linear);
  }

  Widget _toPageViewWidget() {
    return PageView(
      controller: _pageController,
      physics: NeverScrollableScrollPhysics(),
      children: <Widget>[
        _toPullRefreshWidget(
          child: CheckInRecordBrowerGridWidget(
              itemCount: data?.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                return _toGridItemWidget(context,data?.elementAt(index));
              },
            ),
        ),
        _toPullRefreshWidget(
          child: CheckInRecordBrowerListWidget(
              itemCount: data?.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                return _toListItemWidget(context, data?.elementAt(index));
              },
            ),
        ),
      ],
    );
  }


  Widget _toPullRefreshWidget({Widget child}){
    return MixinPlaceHolderStatusWidget(
      emptyOnClick: () => _viewModel.refresh(),
      errorOnClick: ()=> _viewModel.refresh(),
      // loadingOnClick: () => _viewModel?.refresh(),
      child: VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        child: child),
    );
  }

  Widget _toGridItemWidget(BuildContext context, CheckInRecordBrowerForTypeListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        _navigatorPushMakeMarkPage(context,itemBean);
      },
      onLongPress: (){
        _showMenuDialog(context, itemBean);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          fit: StackFit.expand,
          children: [
            VgCacheNetWorkImage(
              itemBean?.pictureUrl ?? "",
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultPlaceType: ImagePlaceType.head,
              defaultErrorType: ImageErrorType.head,
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                width: 32,
                height: 17,
                decoration: BoxDecoration(
                    color:
                        ThemeRepository.getInstance().getMinorRedColor_F95355(),
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(4),
                        bottomLeft: Radius.circular(4))),
                child: Center(
                  child: Text(
                    "标记",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.white, fontSize: 11, height: 1.15),
                  ),
                ),
              ),
            ),
            //遮罩
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 45,
                decoration: BoxDecoration(

                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0x00000000),
                      Color(0x80000000)
                    ]
                  )
                ),
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "${VgToolUtils.getTimestrampStr(itemBean?.punchTime) ?? ""}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                      ),
                    ),
                    Text(
                      "体温${_temperatureStr(itemBean) ?? "0.0"}℃",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color:(double?.parse(itemBean?.temperature??"0") ?? 0) > 37.2 ? ThemeRepository.getInstance().getMinorRedColor_F95355() : Colors.white,
                        fontSize: 10,
                      ),
                    ),
                    Text(
                      "到访${itemBean?.vcnt ?? 0}次",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  String _temperatureStr(CheckInRecordBrowerForTypeListItemBean itemBean){
    if((itemBean?.temperature?.length??0) > 4){
      return itemBean?.temperature?.substring(0,4);
    }else{
      return itemBean?.temperature;
    }
  }

  Widget _toListItemWidget(BuildContext context, CheckInRecordBrowerForTypeListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        _navigatorPushMakeMarkPage(context, itemBean);
      },
      onLongPress: (){
        _showMenuDialog(context, itemBean);
      },
      child: Container(
        height: 60,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Container(
                width: 36,
                height: 36,
                child: VgCacheNetWorkImage(
                  itemBean?.pictureUrl ??"",
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                  defaultPlaceType: ImagePlaceType.head,
                  defaultErrorType: ImageErrorType.head,
                ),
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: Container(
                height: 36,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      itemBean?.punchName ?? "",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getTextMainColor_D0E0F7(),
                          fontSize: 15,
                          height: 1.2),
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          "${VgToolUtils.getTimestrampStr(itemBean?.punchTime) ?? ""}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: VgColors.INPUT_BG_COLOR,
                              fontSize: 12,
                              height: 1.2),
                        ),
                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 8),
                          width: 0.5,
                          height: 10,
                          color:
                              ThemeRepository.getInstance().getLineColor_3A3F50(),
                        ),
                        Text(
                          "${_temperatureStr(itemBean) ??"0.0"}℃",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: VgColors.INPUT_BG_COLOR,
                              // color: ThemeRepository.getInstance()
                              //     .getMinorRedColor_F95355(),
                              fontSize: 12,
                              height: 1.2),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 10),
              child: CommonFixedHeightConfirmButtonWidget(
                width: 60,
                height: 28,
                isAlive: true,
                selectedBgColor:
                    ThemeRepository.getInstance().getMinorRedColor_F95355(),
                unSelectBgColor:
                    ThemeRepository.getInstance().getMinorRedColor_F95355(),
                text: "标记",
                selectedTextStyle:
                    TextStyle(color: Colors.white, fontSize: 13, height: 1.2),
                unSelectTextStyle:
                    TextStyle(color: Colors.white, fontSize: 13, height: 1.2),
              ),
            )
          ],
        ),
      ),
    );
  }

  void _navigatorPushMakeMarkPage(BuildContext context, CheckInRecordBrowerForTypeListItemBean itemBean) async{
    bool result = await MatchingMarkListPage.navigatorPush(context,MarkInfoBean(
      fid: itemBean?.fid,
      picurl: itemBean?.pictureUrl,
    ));
    if(result ?? false){
      CheckInRecordBrowerPageState.of(context).multiRefreshStreamController?.add(null);
    }
  }

  void _showMenuDialog(BuildContext context, CheckInRecordBrowerForTypeListItemBean itemBean){
    CommonMoreMenuDialog.navigatorPushDialog(context,{
      "忽略":(){
        _viewModel?.ignoreSingleFaceHttp(context, itemBean?.fid);
      },
      "删除":(){
        _viewModel?.deleteSingleFaceHttp(context, itemBean?.fid);
      }
    });
  }

  @override
  bool get wantKeepAlive => true;
}
